package com.epfresh.api.global;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.epfresh.api.R;
import com.epfresh.api.constant.Constant;
import com.epfresh.api.entity.User;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.receiver.NetReceiver;
import com.epfresh.api.utils.NetworkUtil;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.MsgView;

/**
 * Created by wzh on 16-6-27.
 */
public class AppActivity extends AppCompatActivity implements View.OnClickListener, NetReceiver.NetEventHandle {
    public TextView basetitle; /* 标题 用于子类 设置标题 */
    public TextView toolbarTitle;
    public TextView rightbtn, rightbtn2;
    public TextView tvBack;
    public ImageView righticon;
    public ImageView baseback;
    public ImageView ivBack;
    public ImageView ivSearch;
    public Context mContext;
    public View v_line;
    public MsgView msg;

    protected RelativeLayout mContentView;
    protected View mainView;
    protected View vException;
    protected View vNetWeakView;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    protected View actionbar;
    protected View toolbar;


    protected TextView tvReload;
    private ProgressBar pb;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 设置禁止横屏
        initContentView();

    }

    private void onNetWeak() {
        Intent intent = new Intent(Settings.ACTION_SETTINGS);

        startActivity(intent);

    }

    protected void onToolbarBack() {
        finish();
    }

    public void onException(int tag) {
    }


    protected void initContentView() {
        mContentView = new RelativeLayout(this);
        actionbar = getToolBar();

    }

    protected View getToolBarView() {

        return inflaterView(R.layout.actionbar_layout, null);
    }

    protected View getToolBar() {
        View actionbar = getToolBarView();

        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.tool_bar_height));
        actionbar.setLayoutParams(lp);

        toolbarTitle = (TextView) actionbar.findViewById(R.id.toolbar_title);/* 标题 用于子类 设置标题 */
        rightbtn = (TextView) actionbar.findViewById(R.id.rightbtn);
        rightbtn2 = actionbar.findViewById(R.id.rightbtn2);
        righticon = (ImageView) actionbar.findViewById(R.id.righticon);//
        ivBack = (ImageView) actionbar.findViewById(R.id.baseback);
        tvBack = (TextView) actionbar.findViewById(R.id.tv_back);
        v_line = actionbar.findViewById(R.id.v_line);
        msg = actionbar.findViewById(R.id.msg);
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivBack.performClick();
            }
        });
        ivBack.setOnClickListener(this);
        baseback = ivBack;
        basetitle = toolbarTitle;
        return actionbar;
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.baseback) {//||id == R.id.tv_back) {
            onToolbarBack();
        } else if (id == R.id.tv_exception || id == R.id.iv_exception) {
            onException((Integer) view.getTag());
        } else if (id == R.id.rl_net_weak) {
            onNetWeak();
        } else if (id == R.id.rightbtn) {
            onRightClick();
        }

    }

    @Override
    public void setContentView(int layoutResID) {
        View view = inflaterView(layoutResID, mContentView);
        this.setContentView(view);
    }

    @Override
    public void setContentView(View view) {
        mContentView.removeAllViews();
        mainView = view;
        vException = inflaterView(R.layout.layout_exception, null);
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
        if (actionbar != null) {

            mContentView.addView(actionbar);

            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            lp2.addRule(RelativeLayout.BELOW, actionbar.getId());
            mContentView.addView(view, lp2);
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            lp1.addRule(RelativeLayout.BELOW, actionbar.getId());
            vException.setVisibility(View.GONE);
            mContentView.addView(vException, lp1);

        } else {
            mContentView.addView(view);
            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            vException.setVisibility(View.GONE);
            mContentView.addView(vException, lp1);
        }

        super.setContentView(mContentView);
    }


    public View inflaterView(int resource, ViewGroup root) {
        LayoutInflater inflater = getLayoutInflater();
        return inflater.inflate(resource, root, false);
    }

    public void onClickReload() {

    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }

    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }

    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }

    public void showNetWeakView() {
        if (vNetWeakView == null) {
            vNetWeakView = inflaterView(R.layout.net_weak_layout, null);

            if (actionbar != null) {
                RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.net_weak_height));
                lp2.addRule(RelativeLayout.BELOW, actionbar.getId());
                mContentView.addView(vNetWeakView, lp2);
            } else {
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, getResources().getDimensionPixelSize(R.dimen.net_weak_height));
                lp.setMargins(0, getResources().getDimensionPixelSize(R.dimen.tool_bar_height), 0, 0);
                vNetWeakView.setLayoutParams(lp);

                mContentView.addView(vNetWeakView);
            }
//            vNetWeakView.setVisibility(View.GONE);
            vNetWeakView.setOnClickListener(this);
        }
        vNetWeakView.setVisibility(View.VISIBLE);
    }

    public void hideNetWeakView() {
        if (vNetWeakView != null) {
            vNetWeakView.setVisibility(View.GONE);
        }
    }

    public void updateNetView() {
        if (vNetWeakView != null) {
            if (NetworkUtil.isNetworkAvailable(this)) {
                vNetWeakView.setVisibility(View.VISIBLE);
            } else {
                vNetWeakView.setVisibility(View.GONE);
            }
        }

    }

    public Dialog progressDialog;

    public boolean isCanceledOnTouchOutside;

    public void showProgressDialog() {

        if (progressDialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_progress, null);

            progressDialog = new Dialog(this, android.support.v7.appcompat.R.style.Theme_AppCompat_DayNight_Dialog);
            progressDialog.setContentView(view);
            Window dialogWindow = progressDialog.getWindow();
            dialogWindow.setGravity(Gravity.CENTER);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = getResources().getDimensionPixelSize(R.dimen.progress_dialog_horizontal);
            lp.height = getResources().getDimensionPixelSize(R.dimen.progress_dialog_vertical);
            dialogWindow.setAttributes(lp);
        }
        progressDialog.setCanceledOnTouchOutside(isCanceledOnTouchOutside);
        progressDialog.show();
    }

//    public void showProgressDialog(boolean isCancel) {
//
//        if (progressDialog == null) {
//            View view = LayoutInflater.from(this).inflate(R.layout.dialog_progress, null);
//
//            progressDialog = new Dialog(this, android.support.v7.appcompat.R.style.Theme_AppCompat_DayNight_Dialog);
//            progressDialog.setContentView(view);
//            progressDialog.setCancelable(isCancel);
//            Window dialogWindow = progressDialog.getWindow();
//            dialogWindow.setGravity(Gravity.CENTER);
//            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//            lp.width = getResources().getDimensionPixelSize(R.dimen.progress_dialog_horizontal);
//            lp.height = getResources().getDimensionPixelSize(R.dimen.progress_dialog_vertical);
//            dialogWindow.setAttributes(lp);
//        }
//        progressDialog.setCanceledOnTouchOutside(isCanceledOnTouchOutside);
//        progressDialog.show();
//    }


    public void hideProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    public User getUser() {
        return ApplicationHelper.getInstance().getUser();
    }


    public void updateUser(User user) {
        ApplicationHelper.getInstance().updateUser(user);
    }

    public void clearUser() {
        ApplicationHelper.getInstance().clearUser();
    }

    //request不能为null
    public <T> void request(Object data, Object tag, OnRequestListener<T> onRequestListener) {

        if (onRequestListener != null)
            onRequestListener.onStart(tag);
        try {
            if (NetworkUtil.isNetworkAvailable(this)) {
                hideNetWeakView();
                ApplicationHelper.getInstance().request(data, tag, new OnTokenInVain() {
                    @Override
                    public void onTokenInVain() {
                        onLogin();
                    }
                }, new AuthCheck() {
                    @Override
                    public void onAuthCheck() {
                        accountAuthCheck();
                    }
                }, onRequestListener);
            } else {
                if (onRequestListener != null)
                    onRequestListener.onFail(HttpRequest.FAIL_NO_NET, null, tag);
                showNetWeakView();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //针对我要买模块添加的修改baseURL
    public <T> void requestBuyer(Object data, Object tag, OnRequestListener<T> onRequestListener) {

        if (onRequestListener != null)
            onRequestListener.onStart(tag);
        try {
            if (NetworkUtil.isNetworkAvailable(this)) {
                hideNetWeakView();
                ApplicationHelper.getInstance().requestBuyer(data,/* Constant.PRODUCT_BASE_URL*/null, tag, new OnTokenInVain() {
                    @Override
                    public void onTokenInVain() {
                        onLogin();
                    }
                }, new AuthCheck() {
                    @Override
                    public void onAuthCheck() {
                        accountAuthCheck();
                    }
                }, onRequestListener);
            } else {
                if (onRequestListener != null)
                    onRequestListener.onFail(HttpRequest.FAIL_NO_NET, null, tag);
                showNetWeakView();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void toast(String content) {
        T.toast(content);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x2379 && resultCode == RESULT_OK) {

        }
    }


    NetReceiver connectionReceiver;

    public void registerNetReceiver() {
        if (connectionReceiver == null) {
            connectionReceiver = new NetReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(connectionReceiver, intentFilter);
    }

    public void unRegisterNetReceiver() {
        if (connectionReceiver != null) {
            unregisterReceiver(connectionReceiver);
        }
    }

    @Override
    protected void onResume() {
        NetReceiver.ehList.add(this);
        registerNetReceiver();
        super.onResume();
        updateNetView();
    }

    @Override
    protected void onPause() {
        NetReceiver.ehList.remove(this);
        unRegisterNetReceiver();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        T.cancel();
        super.onDestroy();
    }

    @Override
    public void netState(NetReceiver.NetState netCode) {

        if (netCode == NetReceiver.NetState.NET_NO) {
            showNetWeakView();
        } else {
            hideNetWeakView();
        }
        switch (netCode) {
            case NET_NO:
                //没有网络连接

                break;
            case NET_2G:
                //2g网络
                break;
            case NET_3G:
                //3g网络
                break;
            case NET_4G:
                //4g网络
                break;
            case NET_WIFI:
                //WIFI网络
                break;
            case NET_UNKNOWN:
                //未知网络
                break;
            default:
                //不知道什么情况
        }
    }


    public void setToolbarTitle(String title) {

        toolbarTitle.setText(title);
    }

    public void setRightText(String text) {
        rightbtn.setText(text);
    }

    public void onRightClick() {

    }

    public void setOnRightVisible(int visible) {
        rightbtn.setVisibility(View.VISIBLE);
    }

    public void setCanToolbarBack(boolean isFinish) {
        ivBack.setVisibility(isFinish ? View.VISIBLE : View.GONE);
        tvBack.setVisibility(isFinish ? View.VISIBLE : View.GONE);
    }


    public void onLogin() {

    }

    public interface OnTokenInVain {
        void onTokenInVain();
    }

    public void accountAuthCheck() {

    }

    public interface AuthCheck {
        void onAuthCheck();
    }


    /*
     * 防止连点
     * */
    long mLastOnClickTime;

    public boolean isWindowLocked() {
        long current = SystemClock.elapsedRealtime();
        if (current - mLastOnClickTime > 1500) {
            mLastOnClickTime = current;
            return false;
        }
        return true;
    }

}
